<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>3.案例-奔跑的小女孩</title>
  <style>
    canvas {
      border: 1px solid red;
    }
  </style>
</head>
<body>
  <canvas width="800" height="600"></canvas>
  <script>
    const canvas = document.querySelector('canvas');
    const ctx = canvas.getContext('2d');

    // 1. 先创建图片实例
    const img = new Image();

    // 2. 加载图片
    img.src = './images/girl.png';
    
    // 3. 当图片加载完成之后再进行裁切或是复制
    img.onload = function () {
      
      // 图片完全加载完成之后才会执行
      ctx.drawImage(img, 0, 256 * 4, 256, 256, 200, 100, 256, 256);

      // 循环构图
      let index = 0;
      setInterval(() => {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        index++;
        if (index > 7) index = 0;
        ctx.drawImage(img, 256 * index, 256 * 4, 256, 256, 200, 100, 256, 256);
      }, 20);
    }
  </script>
</body>
</html>